package jnpf.service.impl;

import jnpf.entity.*;
import jnpf.mapper.RelationMapper;
import jnpf.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.model.relation.*;
import java.math.BigDecimal;
import cn.hutool.core.util.ObjectUtil;
import jnpf.permission.model.authorize.AuthorizeConditionModel;
import jnpf.util.GeneraterSwapUtil;
import jnpf.database.model.superQuery.SuperQueryJsonModel;
import jnpf.database.model.superQuery.ConditionJsonModel;
import jnpf.database.model.superQuery.SuperQueryConditionModel;
import java.lang.reflect.Field;
import com.baomidou.mybatisplus.annotation.TableField;
import java.util.regex.Pattern;
import jnpf.model.QueryModel;
import java.util.stream.Collectors;
import jnpf.base.model.ColumnDataModel;
import jnpf.util.UserProvider;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import jnpf.database.model.superQuery.SuperJsonModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.text.SimpleDateFormat;
import jnpf.util.*;
import java.util.*;
import jnpf.base.UserInfo;
import jnpf.permission.entity.UserEntity;
/**
 *
 * relation
 * 版本： V3.5
 * 版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 * 日期： 2025-04-11
 */
@Service
public class RelationServiceImpl extends ServiceImpl<RelationMapper, RelationEntity> implements RelationService{
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private RelationContentService relationContentService;
    @Override
    public List<RelationEntity> getList(RelationPagination relationPagination){
        return getTypeList(relationPagination,relationPagination.getDataType());
    }
    /** 列表查询 */
    @Override
    public List<RelationEntity> getTypeList(RelationPagination relationPagination,String dataType){
        String userId=userProvider.get().getUserId();
        List<String> AllIdList =new ArrayList();
        List<List<String>> intersectionList =new ArrayList<>();
        boolean isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");
        String columnData = !isPc ? RelationConstant.getAppColumnData() : RelationConstant.getColumnData();
        ColumnDataModel columnDataModel = JsonUtil.getJsonToBean(columnData, ColumnDataModel.class);
        String ruleJson = !isPc ? JsonUtil.getObjectToString(columnDataModel.getRuleListApp()) : JsonUtil.getObjectToString(columnDataModel.getRuleList());

        int total=0;
        int relationNum =0;
        QueryWrapper<RelationEntity> relationQueryWrapper=new QueryWrapper<>();
        int relationContentNum =0;
        QueryWrapper<RelationContentEntity> relationContentQueryWrapper=new QueryWrapper<>();
        long relationContentcount = relationContentService.count();
        List<String> allSuperIDlist = new ArrayList<>();
        String superOp ="";
        if (ObjectUtil.isNotEmpty(relationPagination.getSuperQueryJson())){
            List<String> allSuperList = new ArrayList<>();
            List<List<String>> intersectionSuperList  = new ArrayList<>();
            String queryJson = relationPagination.getSuperQueryJson();
            SuperJsonModel superJsonModel = JsonUtil.getJsonToBean(queryJson, SuperJsonModel.class);
            int superNum = 0;
            QueryWrapper<RelationEntity> relationSuperWrapper = new QueryWrapper<>();
            relationSuperWrapper = generaterSwapUtil.getCondition(new QueryModel(relationSuperWrapper,RelationEntity.class,queryJson,"0"));
            int relationNum1 = relationSuperWrapper.getExpression().getNormal().size();
            if (relationNum1>0){
                List<String> relationList =this.list(relationSuperWrapper).stream().map(RelationEntity::getId).collect(Collectors.toList());
                allSuperList.addAll(relationList);
                intersectionSuperList.add(relationList);
                superNum++;
            }
            String relationContentTable = "relation_content";
            boolean relationContentHasSql = queryJson.contains(relationContentTable);
            List<String> relationContentList = generaterSwapUtil.selectIdsByChildCondition(RelationConstant.getTableList(), relationContentTable , queryJson, null);
            if (relationContentHasSql){
                allSuperList.addAll(relationContentList);
                intersectionSuperList.add(relationContentList);
                superNum++;
            }
            superOp = superNum > 0 ? superJsonModel.getMatchLogic() : "";
            //and or
            if(superOp.equalsIgnoreCase("and")){
                allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
            }else{
                allSuperIDlist = allSuperList;
            }
        }
        List<String> allRuleIDlist = new ArrayList<>();
        String ruleOp ="";
        if (ObjectUtil.isNotEmpty(ruleJson)){
            List<String> allRuleList = new ArrayList<>();
            List<List<String>> intersectionRuleList  = new ArrayList<>();
            SuperJsonModel ruleJsonModel = JsonUtil.getJsonToBean(ruleJson, SuperJsonModel.class);
            int ruleNum = 0;
            QueryWrapper<RelationEntity> relationSuperWrapper = new QueryWrapper<>();
            relationSuperWrapper = generaterSwapUtil.getCondition(new QueryModel(relationSuperWrapper,RelationEntity.class,ruleJson,"0"));
            int relationNum1 = relationSuperWrapper.getExpression().getNormal().size();
            if (relationNum1>0){
                List<String> relationList =this.list(relationSuperWrapper).stream().map(RelationEntity::getId).collect(Collectors.toList());
                allRuleList.addAll(relationList);
                intersectionRuleList.add(relationList);
                ruleNum++;
            }
            String relationContentTable = "relation_content";
            boolean relationContentHasSql = ruleJson.contains(relationContentTable);
            List<String> relationContentList = generaterSwapUtil.selectIdsByChildCondition(RelationConstant.getTableList(), relationContentTable , ruleJson, null);
            if (relationContentHasSql){
                allRuleList.addAll(relationContentList);
                intersectionRuleList.add(relationContentList);
                ruleNum++;
            }
            ruleOp = ruleNum > 0 ? ruleJsonModel.getMatchLogic() : "";
            //and or
            if(ruleOp.equalsIgnoreCase("and")){
                allRuleIDlist = generaterSwapUtil.getIntersection(intersectionRuleList);
            }else{
                allRuleIDlist = allRuleList;
            }
        }
    boolean pcPermission = false;
    boolean appPermission = false;
    if(isPc && pcPermission){
    if (!userProvider.get().getIsAdministrator()){
        Object relationObj=generaterSwapUtil.getAuthorizeCondition(new QueryModel(relationQueryWrapper,RelationEntity.class,relationPagination.getMenuId(),"0"));
        if (ObjectUtil.isEmpty(relationObj)){
        return new ArrayList<>();
        } else {
        relationQueryWrapper = (QueryWrapper<RelationEntity>)relationObj;
        if( relationQueryWrapper.getExpression().getNormal().size()>0){
        relationNum++;
        }
        }
        Object relationContentObj=generaterSwapUtil.getAuthorizeCondition(new QueryModel(relationContentQueryWrapper,RelationContentEntity.class,relationPagination.getMenuId(),"0"));
        if (ObjectUtil.isEmpty(relationContentObj)){
        return new ArrayList<>();
        } else {
        relationContentQueryWrapper = (QueryWrapper<RelationContentEntity>)relationContentObj;
        if( relationContentQueryWrapper.getExpression().getNormal().size()>0){
        relationContentNum++;
        }
        }
    }
    }
    if(!isPc && appPermission){
    if (!userProvider.get().getIsAdministrator()){
        Object relationObj=generaterSwapUtil.getAuthorizeCondition(new QueryModel(relationQueryWrapper,RelationEntity.class,relationPagination.getMenuId(),"0"));
        if (ObjectUtil.isEmpty(relationObj)){
        return new ArrayList<>();
        } else {
        relationQueryWrapper = (QueryWrapper<RelationEntity>)relationObj;
        if( relationQueryWrapper.getExpression().getNormal().size()>0){
        relationNum++;
        }
        }


        Object relationContentObj=generaterSwapUtil.getAuthorizeCondition(new QueryModel(relationContentQueryWrapper,RelationContentEntity.class,relationPagination.getMenuId(),"0"));
        if (ObjectUtil.isEmpty(relationContentObj)){
        return new ArrayList<>();
        } else {
        relationContentQueryWrapper = (QueryWrapper<RelationContentEntity>)relationContentObj;
        if( relationContentQueryWrapper.getExpression().getNormal().size()>0){
        relationContentNum++;
        }
        }


    }
    }
        if(isPc){
            if(ObjectUtil.isNotEmpty(relationPagination.getTableField104_relationId())){
            relationContentNum++;

                String value = relationPagination.getTableField104_relationId() instanceof List ?
                    JsonUtil.getObjectToString(relationPagination.getTableField104_relationId()) :
                    String.valueOf(relationPagination.getTableField104_relationId());
                relationContentQueryWrapper.lambda().like(RelationContentEntity::getRelationId,value);

            }

            if(ObjectUtil.isNotEmpty(relationPagination.getName())){
            relationNum++;

                String value = relationPagination.getName() instanceof List ?
                    JsonUtil.getObjectToString(relationPagination.getName()) :
                    String.valueOf(relationPagination.getName());
                relationQueryWrapper.lambda().like(RelationEntity::getName,value);

            }

        }
        if(!isPc){
            if(ObjectUtil.isNotEmpty(relationPagination.getTableField104_relationId())){
            relationContentNum++;

                String value = relationPagination.getTableField104_relationId() instanceof List ?
                    JsonUtil.getObjectToString(relationPagination.getTableField104_relationId()) :
                    String.valueOf(relationPagination.getTableField104_relationId());
                relationContentQueryWrapper.lambda().like(RelationContentEntity::getRelationId,value);

            }

        }
            if(relationContentNum>0){
            List<String> relationContentIdList = relationContentService.list(relationContentQueryWrapper).stream().filter(t->StringUtil.isNotEmpty(t.getRelationId())).map(t->t.getRelationId()).collect(Collectors.toList());
            long count = relationContentService.count();
            if (count>0){
            intersectionList.add(relationContentIdList);
            }
            AllIdList.addAll(relationContentIdList);
            }
            total+=relationContentNum;
        List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
        if (total>0){
            if (intersection.size()==0){
                intersection.add("jnpfNullList");
            }
            relationQueryWrapper.lambda().in(RelationEntity::getId, intersection);
        }
    //是否有高级查询
        if (StringUtil.isNotEmpty(superOp)){
            if (allSuperIDlist.size()==0){
                allSuperIDlist.add("jnpfNullList");
            }
            List<String> finalAllSuperIDlist = allSuperIDlist;
            relationQueryWrapper.lambda().and(t->t.in(RelationEntity::getId, finalAllSuperIDlist));
        }
    //是否有数据过滤查询
        if (StringUtil.isNotEmpty(ruleOp)){
            if (allRuleIDlist.size()==0){
                allRuleIDlist.add("jnpfNullList");
            }
            List<String> finalAllRuleIDlist = allRuleIDlist;
            relationQueryWrapper.lambda().and(t->t.in(RelationEntity::getId, finalAllRuleIDlist));
        }

        //排序
        if(StringUtil.isEmpty(relationPagination.getSidx())){
            relationQueryWrapper.lambda().orderByDesc(RelationEntity::getId);
        }else{
            try {
                String sidx = relationPagination.getSidx();
                String[] strs= sidx.split("_name");
                RelationEntity relationEntity = new RelationEntity();
                Field declaredField = relationEntity.getClass().getDeclaredField(strs[0]);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                relationQueryWrapper="asc".equals(relationPagination.getSort().toLowerCase())?relationQueryWrapper.orderByAsc(value):relationQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }

        if("0".equals(dataType)){
            if((total>0 && AllIdList.size()>0) || total==0){
                Page<RelationEntity> page=new Page<>(relationPagination.getCurrentPage(), relationPagination.getPageSize());
                IPage<RelationEntity> userIPage=this.page(page, relationQueryWrapper);
                return relationPagination.setData(userIPage.getRecords(),userIPage.getTotal());
            }else{
                List<RelationEntity> list = new ArrayList();
                return relationPagination.setData(list, list.size());
            }
        }else{
            return this.list(relationQueryWrapper);
        }
    }
    @Override
    public RelationEntity getInfo(String id){
        QueryWrapper<RelationEntity> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(RelationEntity::getId,id);
        return this.getOne(queryWrapper);
    }
    @Override
    public void create(RelationEntity entity){
        this.save(entity);
    }
    @Override
    public boolean update(String id, RelationEntity entity){
        return this.updateById(entity);
    }
    @Override
    public void delete(RelationEntity entity){
        if(entity!=null){
            this.removeById(entity.getId());
        }
    }
    /** RelationContent子表方法 */
    @Override
    public List<RelationContentEntity> getRelationContentList(String id,RelationPagination relationPagination){
        Map<String, Object> newtabMap=RelationConstant.TABLEFIELDKEY.entrySet()
        .stream().collect( Collectors.toMap(e->e.getValue(),e->e.getKey()));
        String tableName="relationContent";
        tableName=newtabMap.get(tableName)==null?tableName:newtabMap.get(tableName).toString();
        QueryWrapper<RelationContentEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper = relationContentService.getChild(relationPagination,queryWrapper);
        queryWrapper.lambda().eq(RelationContentEntity::getRelationId, id);
        generaterSwapUtil.wrapperHandle(RelationConstant.getColumnData(), RelationConstant.getAppColumnData(), queryWrapper,RelationContentEntity.class,"sub",tableName);
        return relationContentService.list(queryWrapper);
    }

    /** RelationContent子表方法 */
    @Override
    public List<RelationContentEntity> getRelationContentList(String id){
        QueryWrapper<RelationContentEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(RelationContentEntity::getRelationId, id);
        return relationContentService.list(queryWrapper);
    }
    /** 验证表单唯一字段，正则，非空 i-0新增-1修改*/
    @Override
    public String checkForm(RelationForm form,int i) {
        boolean isUp =StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id="";
        String countRecover = "";
        if (isUp){
            id = form.getId();
        }
        //主表字段验证
                if(StringUtil.isEmpty(form.getName())){
                    return "关系名称不能为空";
                }
        //子表字段验证
            if (form.getRelationContentList()!=null){
            }
        return countRecover;
    }
    /**
    * 新增修改数据(事务回滚)
    * @param id
    * @param relationForm
    * @return
    */
    @Override
    @Transactional
    public void saveOrUpdate(RelationForm relationForm,String id, boolean isSave) throws Exception{
        UserInfo userInfo=userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        relationForm = JsonUtil.getJsonToBean(
        generaterSwapUtil.swapDatetime(RelationConstant.getFormData(),relationForm),RelationForm.class);
        RelationEntity entity = JsonUtil.getJsonToBean(relationForm, RelationEntity.class);

        if(isSave){
            String mainId =  RandomUtil.uuId() ;
        entity.setCreateUserId(userInfo.getUserId());
        entity.setCreateTime(DateUtil.getNowDate());
            entity.setId(mainId);
        }else{
        entity.setCreateUserId(userInfo.getUserId());
        entity.setCreateTime(DateUtil.getNowDate());
        }
        this.saveOrUpdate(entity);

        //RelationContent子表数据新增修改
        if(!isSave){
            QueryWrapper<RelationContentEntity> RelationContentqueryWrapper = new QueryWrapper<>();
            RelationContentqueryWrapper.lambda().eq(RelationContentEntity::getRelationId, entity.getId());
            relationContentService.remove(RelationContentqueryWrapper);
        }
        if (relationForm.getRelationContentList()!=null){
            List<RelationContentEntity> tableField104 = JsonUtil.getJsonToList(relationForm.getRelationContentList(),RelationContentEntity.class);
            for(RelationContentEntity entitys : tableField104){
                entitys.setId(RandomUtil.uuId());
                entitys.setRelationId(entity.getId());
                if(isSave){
                }else{
                }
                relationContentService.saveOrUpdate(entitys);
            }
        }
    }
}
